/*
 * MIT License
 *
 * Copyright (c) 2025 Mark·虎
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 *
 */

package com.hsxxherp.key.uia.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hsxxherp.key.uia.entity.SysAppParameterTemplateVersion;
import com.hsxxherp.key.uia.entity.SysAppVersionTemplateRelation;
import com.hsxxherp.key.uia.entity.SysApplicationVersion;
import com.hsxxherp.key.uia.mapper.SysAppParameterTemplateVersionMapper;
import com.hsxxherp.key.uia.mapper.SysAppVersionTemplateRelationMapper;
import com.hsxxherp.key.uia.mapper.SysApplicationVersionMapper;
import com.hsxxherp.key.uia.service.ISysAppVersionTemplateRelationService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.UUID;

/**
 * 应用版本与模板关系服务实现类
 *
 * @author Mark·虎（2486970363@qq.com）
 */
@Service
public class SysAppVersionTemplateRelationServiceImpl extends ServiceImpl<SysAppVersionTemplateRelationMapper, SysAppVersionTemplateRelation> implements ISysAppVersionTemplateRelationService {

    private static final Logger logger = LoggerFactory.getLogger(SysAppVersionTemplateRelationServiceImpl.class);

    @Autowired
    private SysApplicationVersionMapper sysApplicationVersionMapper;

    @Autowired
    private SysAppParameterTemplateVersionMapper sysAppParameterTemplateVersionMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean createRelation(String appVersionId, String templateVersionId) {
        if (!isAppVersionExists(appVersionId)) {
            handleEntityNotFound("应用版本", appVersionId);
            return false;
        }
        if (!isTemplateVersionExists(templateVersionId)) {
            handleEntityNotFound("模板版本", templateVersionId);
            return false;
        }
        if (isRelationExists(appVersionId, templateVersionId)) {
            handleExistingRelation(appVersionId, templateVersionId);
            return false;
        }
        SysAppVersionTemplateRelation relation = buildRelation(appVersionId, templateVersionId);
        return saveRelation(relation);
    }

    private boolean isAppVersionExists(String appVersionId) {
        QueryWrapper<SysApplicationVersion> appVersionQueryWrapper = new QueryWrapper<>();
        appVersionQueryWrapper.eq("version_id", appVersionId);
        return sysApplicationVersionMapper.selectOne(appVersionQueryWrapper) != null;
    }

    private boolean isTemplateVersionExists(String templateVersionId) {
        QueryWrapper<SysAppParameterTemplateVersion> templateVersionQueryWrapper = new QueryWrapper<>();
        templateVersionQueryWrapper.eq("template_version_id", templateVersionId);
        return sysAppParameterTemplateVersionMapper.selectOne(templateVersionQueryWrapper) != null;
    }

    private boolean isRelationExists(String appVersionId, String templateVersionId) {
        QueryWrapper<SysAppVersionTemplateRelation> relationQueryWrapper = new QueryWrapper<>();
        relationQueryWrapper.eq("app_version_id", appVersionId)
                .eq("template_version_id", templateVersionId);
        return count(relationQueryWrapper) > 0;
    }

    private SysAppVersionTemplateRelation buildRelation(String appVersionId, String templateVersionId) {
        SysAppVersionTemplateRelation relation = new SysAppVersionTemplateRelation();
        relation.setRelationId(UUID.randomUUID().toString());
        relation.setAppVersionId(appVersionId);
        relation.setTemplateVersionId(templateVersionId);
        return relation;
    }

    private boolean saveRelation(SysAppVersionTemplateRelation relation) {
        boolean success = super.save(relation);
        if (success) {
            logger.info("成功创建应用版本 {} 和模板版本 {} 的关联关系", relation.getAppVersionId(), relation.getTemplateVersionId());
        } else {
            logger.error("创建应用版本 {} 和模板版本 {} 的关联关系失败", relation.getAppVersionId(), relation.getTemplateVersionId());
        }
        return success;
    }

    private void handleEntityNotFound(String entityType, String id) {
        logger.error("传入的 {} ID {} 对应的 {} 不存在", entityType, id, entityType);
    }

    private void handleExistingRelation(String appVersionId, String templateVersionId) {
        logger.error("应用版本 ID {} 和模板版本 ID {} 的关联关系已经存在", appVersionId, templateVersionId);
    }
}